Lamda Expression With Example In Java





                                                        

JAVA 1.8 FEATURE


Oracle released a new version of Java as Java 8 in March 18, 2014. It was a revolutionary release of the Java for software development platform. It includes various upgrades to the Java programming, JVM, Tools and libraries.


Java 8 Feature List:-

  • Lambda expressions(Most Important Now a Days)
  • Method references,
  • Functional interfaces***
  • Stream API**
  • Default methods**
  • Base64 Encode Decode,
  • Static methods in interface,
  • Optional class,
  • Collectors class,
  • ForEach() method**
  • Parallel array sorting,
  • Nashorn JavaScript Engine,
  • Parallel Array Sorting,
  • Type and Repating Annotations,
  • IO Enhancements,
  • Concurrency Enhancements,
  • JDBC Enhancements etc.

Java Lambda Expressions

Lambda expression is a new and important feature of Java which was included in Java SE 8. It provides a clear and concise way to represent one method interface using an expression. It is very useful in collection library. It helps to iterate, filter and extract data from collection.

The Lambda expression is used to provide the implementation of an interface which has functional interface. It saves a lot of code. In case of lambda expression, we don't need to define the method again for providing the implementation. Here, we just write the implementation code.

Java lambda expression is treated as a function, so compiler does not create .class file.

Functional Interface

Lambda expression provides implementation of functional interface. An interface which has only one abstract method is called functional interface. Java provides an anotation @FunctionalInterface, which is used to declare an interface as functional interface.


Why use Lambda Expression

  1. To provide the implementation of Functional interface.
  2. Less coding.

Java Lambda Expression Syntax

  1. (argument) -> {body}  
  2. 1) Argument: It can be empty or non-empty as well.
  3. 2) Arrow: It is used to link arguments-list and body of expression.

    3) Body: It contains expressions and statements for lambda expression.

No Parameter Syntax

  1. () -> {  
  2. //Body of no parameter lambda  
  3. }  

One Parameter Syntax

  1. (p1) -> {  
  2. //Body of single parameter lambda  
  3. }  

Two Parameter Syntax

  1. (p1,p2) -> {  
  2. //Body of multiple parameter lambda  
  3. }  
  4. Please note: Lambda expressions are just like functions and they accept parameters just like functions.

    // A Java program to demonstrate simple lambda expressions
    import java.util.ArrayList;
    class Test
    {
        public static void main(String args[])
        {
            // Creating an ArrayList with elements
            // {1, 2, 3, 4}
            ArrayList<Integer> arrL = new ArrayList<Integer>();
            arrL.add(1);
            arrL.add(2);
            arrL.add(3);
            arrL.add(4);
      
            // Using lambda expression to print all elements
            // of arrL
            arrL.forEach(n -> System.out.println(n));
      
            // Using lambda expression to print even elements
            // of arrL
            arrL.forEach(n -> { if (n%2 == 0) System.out.println(n); });
        }

    IMPORTANT NOTE:-

    Note that lambda expressions can only be used to implement functional interfaces. In the above example also, the lambda expression implements Consumer Functional Interface.

    public class Test
    {
        // operation is implemented using lambda expressions
        interface FuncInter1
        {
            int operation(int a, int b);
        }
      
        // sayMessage() is implemented using lambda expressions
        // above
        interface FuncInter2
        {
            void sayMessage(String message);
        }
      
        // Performs FuncInter1's operation on 'a' and 'b'
        private int operate(int a, int b, FuncInter1 fobj)
        {
            return fobj.operation(a, b);
        }
      
        public static void main(String args[])
        {
            // lambda expression for addition for two parameters
            // data type for x and y is optional.
            // This expression implements 'FuncInter1' interface
            FuncInter1 add = (int x, int y) -> x + y;
      
            // lambda expression multiplication for two parameters
            // This expression also implements 'FuncInter1' interface
            FuncInter1 multiply = (int x, int y) -> x * y;
      
            // Creating an object of Test to call operate using
            // different implementations using lambda Expressions
            Test tobj = new Test();
      
            // Add two numbers using lambda expression
            System.out.println("Addition is " +
                              tobj.operate(6, 3, add));
      
            // Multiply two numbers using lambda expression
            System.out.println("Multiplication is " +
                              tobj.operate(6, 3, multiply));
      
            // lambda expression for single parameter
            // This expression implements 'FuncInter2' interface
            FuncInter2 fobj = message ->System.out.println("Hello "
                                                     + message);
            fobj.sayMessage("Geek");
        }
    }

Comments